package com.cxp.serverdemo.config;

import com.cxp.serverdemo.Repository.RoleRepository;
import com.cxp.serverdemo.Repository.UserRepository;
import com.cxp.serverdemo.bean.sys.bean.Role;
import com.cxp.serverdemo.bean.sys.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;

    private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        logger.info("CustomUserDetailsService.username-------------------" + s);
        User user = userRepository.findByUsername(s);
        logger.info("CustomUserDetailsService.user-----------------------" + user);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        logger.info("CustomUserDetailsService.user:::::" + user.toString());
        logger.info("CustomUserDetailsService.user:::::" + user.getUsername());
        List<Role> roles = roleRepository.findRolesByUsername(user.getUsername().toString());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role:roles){
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
            logger.info("CustomUserDetailsService.roleName:::::" + role.getName());
        }
        user.setAuthorities(authorities);
        return user;
    }
}
